<?php
namespace Home\Controller;
/**
 * 提现日志
 * @author Administrator
 *
 */
class DepositlogController extends HomeBaseController
{
    /**
     * 提现记录页
     */
    public function index(){
        $arry=array('uid' => session('uid'));
        $count = D('DepositLog')->getCount($arry);
        $list = D('DepositLog')->getDepositLog($arry);
        
        $condition['uid'] = session('uid');
        $user_assets = D('user_assets')->field(true)->where($condition)->find();
        
        $this->assign('userAssets', $user_assets);
        $this->assign('list', $list);
        $this->assign('count', $count);
        $this->display("depositLog/index");
    }
    /**
     * 提现申请页
     */
    public function applyDeposit(){
            $con1['uid'] = session('uid');
            $bankList = M('user_bank')->where($con1)->select();
            
            $con2['uid'] = session('uid');
            $con2['status'] = 1;
            $con2["is_use_dep"] = 2;
            $con2["Date(expiredate)"] = array('egt', date('Y-m-d', time()));
            $userPacket = M('UserPacket')->where($con2)->select();
            
            $con3['uid'] = session('uid');
            $user_assets = D('user_assets')->field(true)->where($con3)->find();
            
            
            $con4['type'] = 1;//提现手续费率
            $tradeFee = M('trade_fee')->field(true)->where($con4)->find();
            
            $con5['id'] = session('uid');
            $user = M('user')->field(true)->where($con5)->find();
            
            $this->assign('userAssets', $user_assets);
            $this->assign('bankList', $bankList);
            $this->assign('userPacket', $userPacket);
            $this->assign('tradeFee', $tradeFee["rate"]);
            $this->assign('mobile', $user["mobile"]);
            $this->display("depositLog/apply");
        }
        
        /**
         * 保存提现申请
         */
        public function saveDeposit(){
            $resp['status']=0;
            $resp['msg']="提现申请失败！";
            
            //1 校验短信验证码
            $result = D('Mess','Event')->checkCode(I('post.codeMobile',''));
            if($result["status"] == 0){
                $this->ajaxReturn($result,'JSON');
                exit();
            }else{
                session('registerCode',null);
            };
            //2 校验支付密码
            $user = M('user')->field(true)->where(array('id'=> session('uid')))->find();
            if(strtolower(md5(I("post.transpasswd",0))) != strtolower($user["transpasswd"])){
                $resp['msg']="支付密码错误！";
                $this->ajaxReturn($resp,'JSON');
                exit();
            };
            $dep_type=I('dep_type','');
            $dod['uid']=session('uid');
            $dod['id']=$dep_type;
            $bank=M('UserBank')->field('bankname,fullname,username,bankcode')->where($dod)->select();
            if(empty($bank)){
                $resp['msg']="用户银行卡错误！";
                $this->ajaxReturn($resp,'JSON');
                exit();
            }
            $bank=$bank[0];
            
            $depmoney=I("post.dep_money",0);
            $useAset=M('UserAssets')->where('uid='.session('uid'))->select();
            $useAset=$useAset[0];
            if($useAset['present_money']<$depmoney){
                $resp['msg']="实际可提现金额小于提现金额！";
                $this->ajaxReturn($resp,'JSON');
                exit();
            }
            //3 保存提现记录
            $arry=array(
                'uid' => session('uid'),
                'dep_money' => $depmoney,
                'dep_fee' => I("post.dep_fee",0),
                'dep_coupon' => I("post.dep_coupon",0),
                'actual_money' => I("post.actual_money",0),
                'dep_type' => I("post.dep_type",1),
                'dep_cardno' => $bank['bankcode'],
                'userremark' => I("post.userremark",""),
                'packet_id' => I("post.user_packet",0),
                'bankname'=>$bank['bankname'].'-'.$bank['fullname'],
                'accountname'=>$bank['username'],
            );
            
             $result = D('DepositLog')->inserDepositLog($arry);
            if($result['status'] == 1){
                //4 操作用户资金
                $con3['uid'] = session('uid');
                $user_assets = M('user_assets')->field(true)->where($con3)->find();
                $money['avail_money'] = $user_assets["avail_money"]-I("post.actual_money",0)-I("post.dep_fee",0);
                $money['present_money'] = $user_assets["present_money"]-I("post.actual_money",0)-I("post.dep_fee",0);
                $money['locked_money'] = $user_assets["locked_money"]+I("post.actual_money",0)+I("post.dep_fee",0);
                M('user_assets')->where(array('uid'=> session('uid')))->save($money);
                
                //5 操作用户福利
                if(I("post.user_packet",0) != 0){
                    $packet['status'] = 2;
                    M('user_packet')->where(array('id'=> I("post.user_packet")))->save($packet);
                };
                
                //6 添加流水
                /* $detail=array(
                    'uid' => session('uid'),
                    'tran_income' => 3,
                    'flow_money' => I("post.actual_money",0)+I("post.dep_fee",0),
                    'balance' =>$money['avail_money'],
                    'tran_type' => 2,
                    'userremark' => I("post.userremark",""),
                );
                D('UserCaptdetail')->inser($detail); */
                $resp['status']=1;
                $resp['msg']="提现申请成功！";
            }else{
                $resp['msg']=$result['msg'];
            };
            $this->ajaxReturn($resp,'JSON');
        }
        
        /**
         * 取消提现申请
         */
        public function cancelDeposit(){
            $resp['status']=0;
            $resp['msg']="撤单失败！";
            // 1 查询提现日志
            $depositLog = M('deposit_log')->where(array('id'=> I("post.id")))->find();
            
            // 2 操作账户资金
            $con3['uid'] = session('uid');
            $user_assets = M('user_assets')->field(true)->where($con3)->find();
            $money['avail_money'] = $user_assets["avail_money"]+$depositLog["actual_money"]+$depositLog["dep_fee"];
            $money['present_money'] = $user_assets["present_money"]+$depositLog["actual_money"]+$depositLog["dep_fee"];
            $money['locked_money'] = $user_assets["locked_money"]-$depositLog["actual_money"]-$depositLog["dep_fee"];
            M('user_assets')->where(array('uid'=> session('uid')))->save($money);
            
            // 3 操作福利记录
            if( null != $depositLog["packet_id"] & $depositLog["packet_id"] != 0){
                $packet['status'] = 1;
                M('user_packet')->where(array('id'=> $depositLog["packet_id"]))->save($packet);
            };
            // 3 操作提现日志
            $result = M('deposit_log')->where(array('id'=> I("post.id")))->setField('status',3);
            if($result !== false){
                $resp['status']=1;
                $resp['msg']="撤单成功！";
            };
            //4 添加流水
            /* $detail=array(
                'uid' => session('uid'),
                'tran_income' => 3,
                'flow_money' => $depositLog["actual_money"]+$depositLog["dep_fee"],
                'balance' =>$money['avail_money'],
                'tran_type' => 2,
            ); 
            D('UserCaptdetail')->inser($detail);*/
            $this->ajaxReturn($resp,'JSON');
        }
        
        
    /**
     * 流水查询
     */
    public function getCaptDetail(){
        $list = D('UserCaptdetail')->getList(session('uid'),I('post.queryTime',1));
        $count = D('UserCaptdetail')->getCount(session('uid'),I('post.queryTime',1));
        $condition['uid'] = session('uid');
        $userAssets = D('user_assets')->field(true)->where($condition)->find();
        $this->assign('list', $list);
        $this->assign('count', $count);
        $this->assign('userAssets', $userAssets);
        $this->assign('queryTime', I('post.queryTime',1));
        $this->display("depositLog/captdetail");
    }
    
    
    /**
     * 流水查询exportexcel($data=array(),$title=array(),$filename='report'){
     */
    public function exportexcel(){
        $xlsName  = "流水明细";
        $xlsCell  = array(
            array('id','ID'),
            array('flow_money','流水'),
            array('balance','余额'),
            array('tran_income','类型'),
            array('createdate','发生时间'),
            array('userremark','用户备注'),
        );
        $xlsData =M('user_captdetail')->Field('id,flow_money,balance,tran_income,createdate,userremark')->where(array('uid'=> session('uid')))->select();
        foreach ($xlsData as $k => $v){
            $type="现金红包";
            if($v['tran_income']==2){
                $type="支付充值";
            }elseif ($v['tran_income']==3){
                $type="银行卡提现";
            }elseif ($v['tran_income']==4){
                $type="域名交易费";
            }elseif ($v['tran_income']==5){
                $type="手续费";
            };
            $xlsData[$k]['tran_income']=$type;
        };
        $this->exportExcelData($xlsName,$xlsCell,$xlsData);
    }
    
    
    public function exportExcelData($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName =$expTitle;//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle);
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        };
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
}